//
//  ST_QuickChatFloatableControl.swift
//  btvideo
//
//  Created by Jason on 2022/2/28.
//  Copyright © 2022 JarvanZhang. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import SwiftyAttributes



private class ST_QuickChatFloatableControl: UIControl {
    
    let sessionId:String
    
    init(sessionId:String,msg:NSAttributedString){
        
        self.sessionId = sessionId
        
        super.init(frame: .zero)
        addSubviews([avatar_image_view,titleLabel,msg_label,reply_btn])
        
        avatar_image_view.snp.makeConstraints { make in
            make.width.height.equalTo(40)
            make.left.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview().offset(-11)
            make.left.equalTo(avatar_image_view.snp.right).offset(7)
            make.height.equalTo(20)
        }
        
        msg_label.snp.makeConstraints { make in
            make.centerY.equalToSuperview().offset(11)
            make.left.equalTo(avatar_image_view.snp.right).offset(7)
            make.height.equalTo(18)
            make.right.equalTo(reply_btn.snp.left).offset(-7)
        }
        
        reply_btn.snp.makeConstraints { make in
            make.width.equalTo(57)
            make.height.equalTo(28)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
        }
        
        msg_label.attributedText = msg
        
        BINP.update_displaying_subject.debounce(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).subscribe(onNext: {[weak self] in
            
            if let info = BINP.fetch_nickname_with_avatar(userId: self?.sessionId ?? ""){
                
                self?.avatar_image_view.pin_setImage(from: info.avatar.compress_small_image(width: 40*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
                
                self?.titleLabel.text = info.userName
                
                self?.alpha = 1
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: {
                
                    self?.removeFromSuperview()
                
                })
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleAspectFill
        v.clipsToBounds = true
        //v.cornerRadius = 5
        return v
    }()
    
    
    fileprivate lazy var titleLabel:UILabel = {
        let l = UILabel()
        l.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        l.font = .systemFont(ofSize: 14, weight: .medium)
        return l
    }()
    
    fileprivate lazy var msg_label:UILabel = {
        let l = UILabel()
        l.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        l.font = .systemFont(ofSize: 13, weight: .regular)
        return l
    }()
    
    fileprivate lazy var reply_btn:UIButton = {
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.setAttributedTitle("回复".withAttributes([.font(.systemFont(ofSize: 13, weight: .medium)),.textColor(.white)]), for: .normal)
        btn.backgroundColor = UIColor(hex: 0xFEC207)
        btn.cornerRadius = 14
        //btn.cornerRadius = 0
        //btn.semanticContentAttribute = .forceRightToLeft
        btn.addTarget(self, action: #selector(click_handle), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    @objc func click_handle(){
        
        let vc = ST_PrivateChatViewController()
        
        vc.sessionID = sessionId
        
        vc.source = "聊天列表"
        
        self.parentViewController?.navigationController?.pushViewController(vc)
    }
    
    private var shadowLayer: CAShapeLayer!
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if shadowLayer == nil {
            shadowLayer = CAShapeLayer()
            shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 10).cgPath
            shadowLayer.fillColor = UIColor.white.cgColor
            
            shadowLayer.shadowColor = UIColor(white: 0, alpha: 0.7).cgColor
            shadowLayer.shadowPath = shadowLayer.path
            shadowLayer.shadowOffset = CGSize(width: 2.0, height: 2.0)
            shadowLayer.shadowOpacity = 1
            shadowLayer.shadowRadius = 11
            
            layer.insertSublayer(shadowLayer, at: 0)
            //layer.insertSublayer(shadowLayer, below: nil) // also works
        }
    }
}


class ST_QuickChatFloatableControlDispatcher:NSObject{
    
    private var itemView:ST_QuickChatFloatableControl?
    
    var isHidden = false{
        didSet{
            self.itemView?.isHidden = isHidden
        }
    }
    
    func start(root_view:UIView){
        
        Observable.combineLatest(SCComponets.login_status_did_changed_observable(), ST_ConversationAdapter.shared.added_element_observer,ST_BTLaunchController.shared.advertStatus).observe(on: MainScheduler.instance).subscribe(onNext: { arg in
            
            self.itemView?.removeFromSuperview()
            
            let first = arg.1
            
            if arg.0,arg.2 == .finished,!first.lastMsgSent{
                
                let control = ST_QuickChatFloatableControl(sessionId: first.sessionId, msg: first.lastMessage)
                control.alpha = 0
                root_view.addSubview(control)
                
                control.snp.makeConstraints { make in
                    make.left.equalToSuperview().offset(18)
                    make.right.equalToSuperview().offset(-18)
                    make.height.equalTo(70)
                    make.top.equalToSuperview().offset(statusBarHeight+44-20)
                }
                self.itemView = control
                
                control.isHidden = self.isHidden
            }
            
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    
}


